package com.platform.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.platform.comm.dto.DtoMapper;
import com.platform.comm.jwt.TokenInfoUtil;
import com.platform.comm.service.impl.CommonBizImpl;
import com.platform.core.entity.NcloudSysNotifyUserEntity;
import com.platform.core.entity.QNcloudSysNotifyEntity;
import com.platform.core.entity.QNcloudSysNotifyUserEntity;
import com.platform.core.repository.NcloudSysNotifyUserRepository;
import com.platform.core.service.NcloudSysNotifyUserBiz;
import com.platform.dto.NcloudSysNotifyDto;
import com.platform.enums.SysNotifyUserType;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Description: DirNotifyUser-业务接口实现类
 *
 * @author zq
 */
@Slf4j
@Service
public class NcloudSysNotifyUserBizImpl extends CommonBizImpl<NcloudSysNotifyUserRepository, NcloudSysNotifyUserEntity, String> implements NcloudSysNotifyUserBiz {

    private final QNcloudSysNotifyUserEntity qNcloudSysNotifyUser = QNcloudSysNotifyUserEntity.qNcloudSysNotifyUserEntity;
    private final QNcloudSysNotifyEntity qNcloudSysNotify = QNcloudSysNotifyEntity.dirNotifyEntity;
    private final JPAQueryFactory queryFactory;
    private final TokenInfoUtil tokenInfoUtil;
    private final DtoMapper mapper;

    public NcloudSysNotifyUserBizImpl(NcloudSysNotifyUserRepository ncloudSysNotifyUserRepository, JPAQueryFactory queryFactory,
                                      TokenInfoUtil tokenInfoUtil,DtoMapper mapper) {
        super(ncloudSysNotifyUserRepository);
        this.queryFactory = queryFactory;
        this.tokenInfoUtil = tokenInfoUtil;
        this.mapper = mapper;
    }

    @Override
    public void saveAll(List<NcloudSysNotifyUserEntity> entities) {
        repository.saveAll(entities);
    }

    @Override
    public void removeByNotifyId(String notifyId) {
        Iterable<NcloudSysNotifyUserEntity> all = repository.findAll(qNcloudSysNotifyUser.notifyId.eq(notifyId));
        repository.deleteInBatch(all);
    }

    @Override
    public Page<NcloudSysNotifyDto> search(Map<String, String> params, Pageable pageable) {
        String readStatus = Optional.ofNullable(params).map(map -> map.get("readStatus")).orElse("");
        String title = Optional.ofNullable(params).map(map -> map.get("title")).orElse("");
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qNcloudSysNotifyUser.userId.eq(tokenInfoUtil.getUser().getId()));
        if (StrUtil.isNotBlank(readStatus)) {
            builder.and(qNcloudSysNotifyUser.status.eq(readStatus));
        } else {
            builder.and(qNcloudSysNotifyUser.status.in(SysNotifyUserType.UNREAD.name(), SysNotifyUserType.READED.name()));
        }
        if (StrUtil.isNotBlank(title)) {
            builder.and(qNcloudSysNotify.title.contains(title));
        }
        // 截止日期大于当前日期
//        builder.and(qNcloudSysNotify.deadlineDate.after(LocalDate.now()));
        return repository.findAll(new BooleanBuilder(), pageable
                , jpqlQuery -> jpqlQuery.from(qNcloudSysNotifyUser).leftJoin(qNcloudSysNotify).on(qNcloudSysNotifyUser.notifyId.eq(qNcloudSysNotify.id))
                        .where(builder)
                        .orderBy(qNcloudSysNotify.createDate.desc(),qNcloudSysNotify.status.asc())
                , qNcloudSysNotifyUser.status, qNcloudSysNotify).map(tuple -> {
            NcloudSysNotifyDto sysNotifyDto = mapper.map(tuple.get(qNcloudSysNotify), NcloudSysNotifyDto.class);
            sysNotifyDto.setReadStatus(tuple.get(qNcloudSysNotifyUser.status));
            return sysNotifyDto;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyAllStatus(String status, Map<String, String> paramters) {
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qNcloudSysNotifyUser.userId.eq(tokenInfoUtil.getUser().getId()));
        if (SysNotifyUserType.READED.name().equals(status)) {
            builder.and(qNcloudSysNotifyUser.status.eq(SysNotifyUserType.UNREAD.name()));
        }
        if (NcloudSysNotifyUserBiz.DEL.equals(status)) {
            String dataStatus = Optional.ofNullable(paramters).map(map -> map.get("status")).orElse("");
            if (StrUtil.isNotBlank(dataStatus)) {
                builder.and(qNcloudSysNotifyUser.status.eq(dataStatus));
            } else {
                builder.and(qNcloudSysNotifyUser.status.in(SysNotifyUserType.UNREAD.name(), SysNotifyUserType.READED.name()));
            }
        }
        queryFactory.update(qNcloudSysNotifyUser)
                .set(qNcloudSysNotifyUser.status, status)
                .set(qNcloudSysNotifyUser.updateDate, LocalDateTime.now())
                .where(builder).execute();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyStatus(String status, String notifyId) {
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qNcloudSysNotifyUser.userId.eq(tokenInfoUtil.getUser().getId()));
        builder.and(qNcloudSysNotifyUser.notifyId.eq(notifyId));
        Optional<NcloudSysNotifyUserEntity> optional = queryOne(builder);
        NcloudSysNotifyUserEntity entity = optional.get();
        entity.setStatus(status);
        entity.setUpdateDate(LocalDateTime.now());
        saveEntity(entity);
    }
}
